

//  CLVideoViewController.m
//  chanlin
//
//  Created by Ryan on 14-12-16.
//  Copyright (c) 2014年 chanlin. All rights reserved.
//

#import "CLVideoViewController.h"
#import "CLDocModel.h"
#import "UIImageView+WebCache.h"
#import "UIView+Utils.h"
#import "BlockUI.h"
#import "IFMoviePlayerController.h"
#import "CLGloble.h"
#import "IFIndexTitleCell.h"
#import "IFIndexIconCell.h"
#import "CLSlidersViewController.h"
#import "CLPushAnimatedRight.h"
#import "CLDocViewController.h"
#import "CLTopicViewController.h"
#import "CTCommentViewController.h"
#import "PanPushAnimationFromRight.h"
#import "CLNavigationController.h"
#import "CLComentDataModel.h"
#import "CLGlobleDataModel.h"

#define LIVEMOVIEPLAYERHEIGHT 180.0

@interface CLVideoViewController ()

@property (nonatomic,strong)UIImageView *videoImg;
@property (nonatomic,strong)UIActivityIndicatorView *active;
@property (nonatomic,strong)UIButton *play;
@property (nonatomic,strong) CLDocEntity *entity;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) CTCommentViewController *commentVC;
@property (nonatomic,strong) PanPushAnimationFromRight *panpushAnimation;
@property (nonatomic,strong)NSString *commnetDocID;
@property (nonatomic,strong) IFMoviePlayerController *pc;

@end

@implementation CLVideoViewController

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    if(self.pc){
        [[CLGloble sharedInstance] clearMovie];
    }
    [((CLNavigationController *)[self k_rootController]).panGesture removeTarget:self
                                                                          action:@selector(doPanRecognizer:)];

    
}

- (void)viewDidLoad {
    self.view.backgroundColor=[UIColor whiteColor];
    self.videoImg=[[UIImageView alloc] initWithFrame:CGRectMake(0, 20.f, GlobleWidth, LIVEMOVIEPLAYERHEIGHT)];
    self.videoImg.userInteractionEnabled=YES;
    [self.view addSubview:self.videoImg];
    
    self.play=[UIButton buttonWithType:UIButtonTypeCustom];
    self.play.frame=CGRectMake(0, 0, 76, 76);
    [self.play setImage:[UIImage imageNamed:@"doc_playImage.png"] forState:UIControlStateNormal];
    self.play.contentEdgeInsets=UIEdgeInsetsMake(14, 14, 14, 14);
    [self.play setCenter:CGPointMake(self.videoImg.width/2.f, self.videoImg.height/2.f)];
    [self.videoImg addSubview:self.play];

    
    self.active=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.active.frame=CGRectMake(0, 0, 45.f, 45.f);
    [self.active setCenter:CGPointMake(self.view.frame.size.width/2.f, self.view.frame.size.height/2.f)];
    [self.view addSubview:self.active];
    [self.active startAnimating];
    
    self.tableView=[[UITableView alloc] init];
    self.tableView.frame=CGRectMake(0, self.videoImg.bottom, GlobleWidth, GlobleHeight-self.videoImg.bottom);
    
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.tableView.scrollsToTop=NO;
   
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor=[UIColor whiteColor];
    UIView *bg=[[UIView alloc] init];
    self.tableView.backgroundView=bg;
    bg.backgroundColor=[UIColor whiteColor];
    self.tableView.backgroundView=bg;
    [self.view addSubview:self.tableView];
    self.tool=[self showToolbarWithType:IFActive_ButtomToolBarButtonTypeCollect|IFActive_ButtomToolBarButtonTypeShare|IFActive_ButtomToolBarButtonTypeShowComment|IFActive_ButtomToolBarButtonTypeWriteComment];
    __weak typeof(self) me=self;
    [self.tool handleTap:IFActive_ButtomToolBarButtonTypeShare block:^(id sender) {
        if(_isStrNULL(me.entity.shareUrl)){
            [[CLGloble sharedInstance] showTieSuccessMessage:@"现在不能分享" subMessage:@"缺少分享地址"];
            return ;
        }
        
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
//        [dic sgrSetObject:[UIImage imageNamed:@"icon114.png"] forKey:@"icon"];
        [dic sgrSetObject:[me getImageFromURL:me.entity.sharepicUrl] forKey:@"icon"];
        
        [dic sgrSetObject:me.entity.title forKey:@"title"];
        [dic sgrSetObject:me.entity.shareUrl forKey:@"url"];
        [me openShare:dic];
    }];
    
    [self.tool handleTap:IFActive_ButtomToolBarButtonTypeWriteComment block:^(id sender) {
        if(_isStrNULL(me.commnetDocID)){
            [[CLGloble sharedInstance] showTieAlertMessage:@"暂时不能评论" subMessage:@"请稍后尝试"];
            return ;
        }
        [me openComment:me.commnetDocID replayId:nil block:^(NSString *cont, int select) {
            NSString *str=[NSString stringWithFormat:@"我的评论:%@ |%@ %@",_safeStr(cont),_safeStr(me.entity.title),
                           _safeStr(me.entity.shareUrl)];
            [[CLGlobleDataModel sharedInstance] shareMessage:select content:str];
        }];
    }];
    [self.tool handleTap:IFActive_ButtomToolBarButtonTypeShowComment block:^(id sender) {
        [me.panpushAnimation pushDirectly];
    }];

    
    self.tool.collectId=self.itemId;
    
 
    [[CLDocModel sharedInstance] getDoc:self.itemId
                                uiBlock:^(BOOL success, CLDocEntity *responseObj, NSString *message) {
                                    if(success){
                                        me.entity=responseObj;
                                        if(_isStrNotNull(responseObj.bigpic))
                                        [me.videoImg sd_setImageWithURL:[NSURL URLWithString:responseObj.bigpic]
                                                       placeholderImage:nil];
                                        [me.tableView reloadData];
                                    }else{
                                        
                                    }
                                    [me.active stopAnimating];
                                    
                                    [me requestComment];
                                   
                                    [MobClick event:@"page"
                                         attributes:@{@"pageId":[@"video_" stringByAppendingString:_safeStr(me.entity.itmeId)],
                                                      @"title":_safeStr(me.entity.title)}];

                                }];
    
    
  
    [self.play handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        if (me.entity.vurl&& [me.entity.vurl length] > 4){
            [[CLGloble sharedInstance] clearMovie];
            CGRect frame=me.videoImg.frame;
            IFMoviePlayerController *moviePlayer = [[IFMoviePlayerController alloc] initWithContentURL:nil WithType:IFVideo_Type_Document];
            //self.moviePlayer.delegate = self;
            //self.moviePlayer.repeatMode = MPMovieRepeatModeOne;
            me.pc=moviePlayer;
            [moviePlayer.view setFrame:frame];
            
            //IEmbedMoviePlayer *player=[[IEmbedMoviePlayer alloc] initWithFrame:frame];
            //        IEmbedMoviePlayer *player =[IEmbedMoviePlayer getEmbedMoviePlayer:frame];
            //              [player setframe:frame];
            //        player.playerController.videoIdStr = self.documentId;
            //        self.moviePlayer = player;
            [me.view addSubview:moviePlayer.view];
            
            [moviePlayer setContentURL:[NSURL URLWithString:me.entity.vurl]];
            [moviePlayer prepareToPlay];
            [moviePlayer play];
            [CLGloble sharedInstance].singleMovie=moviePlayer;
            
            
        }
    }];
    
    if(!self.commentVC){
        self.commentVC = [[CTCommentViewController alloc] init];
        self.commentVC.isNeedRequest=NO;
        self.commentVC.fromtype=@"doc";
        self.panpushAnimation=[[PanPushAnimationFromRight alloc] init];
        // self.panpushAnimation.pathName=self.document.documentId;
        [self.panpushAnimation addNextController:self.commentVC];
        // self.panpushAnimation.animationType=Dispatch_AnimationType_push;
        
        [((CLNavigationController *)[self k_rootController]).panGesture addTarget:self action:@selector(doPanRecognizer:)];
    }

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(deviceChangeOrientationNotification:)
                                                 name:UIDeviceOrientationDidChangeNotification
                                               object:nil];

}


- (void)deviceChangeOrientationNotification:(NSNotification*)notification{
    if(![CLGloble sharedInstance].singleMovie) return;
    
    if([CLGloble sharedInstance].singleMovie.fullscreen&&
       UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation])){
        [[CLGloble sharedInstance].singleMovie setFullscreen:NO animated:YES];
    }else if(![CLGloble sharedInstance].singleMovie.fullscreen&&
              UIDeviceOrientationIsLandscape([[UIDevice currentDevice] orientation])){
        [[CLGloble sharedInstance].singleMovie setFullscreen:YES animated:NO];
    }
}


- (void)requestComment{
    __weak typeof(self) me=self;
    [[CLComentDataModel sharedInstance] loadTopicWithUrl:nil
                                                   title:self.entity.title
                                                     doc:self.itemId
                                                   block:^(BOOL success, NSDictionary *dic) {
                                                       if(success){
//                                                           me.document.commentsArray=[[dic sgrGetDictionaryForKey:@"comments"] sgrGetArrayForKey:@"newest"];
                                                           me.commentVC.docTitle=me.entity.title;
                                                           me.commentVC.shareUrl=me.entity.shareUrl;
                                                           me.commnetDocID=[dic sgrFGetStringForKey:@"topic_id"];
                                                           me.commentVC.commentTopicId=me.commnetDocID;
                                                           [me.tool update:[dic sgrGetIntForKey:@"count"]];
                                                           
                                                           [me.commentVC showCommentDic:dic];
                                                           
                                                       }else{
                                                           
                                                       }
                                                       // NSLog(@"%@",dic);
                                                       
                                                   }];
}

- (void)doPanRecognizer:(UIPanGestureRecognizer *)recognizer{
    if(self!=[self k_currentController])return;
    
    [self.panpushAnimation doAnimation:recognizer];
    

}

-(UIImage *)getImageFromURL:(NSString *)fileURL {
    UIImage * result;
    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
    result = [UIImage imageWithData:data];
    if (result) {
        return result;
    }else
        return [UIImage imageNamed:@"icon114.png"];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.entity.relation?[self.entity.relation count]:0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    return 78.f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *dic=[self.entity.relation sgrGetDictionaryForIndex:indexPath.row];
    
    NSString *str=[dic sgrGetStringForKey:@"titlepic"];
    
    if(_isStrNULL(str)){
        static NSString *cellID=@"IFIndexTitleCell";
        IFIndexTitleCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        if(!cell){
            cell=[[IFIndexTitleCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        [cell loadDic:dic];
        return cell;
    }else{
        static NSString *cellID=@"IFIndexIconCell";
        IFIndexIconCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        if(!cell){
            cell=[[IFIndexIconCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        
        [cell loadDic:dic];
        int linkType=[[dic sgrFGetStringForKey:@"type"] intValue];
        
            [cell setPlayVideo:linkType==CLList_video];
    
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dic=[self.entity.relation sgrGetDictionaryForIndex:indexPath.row];
    [self clickOnList:dic];
}

- (void)clickOnList:(NSDictionary *)list{
    int linkType=[[list sgrFGetStringForKey:@"type"] intValue];
    NSString *itemId=[list sgrGetStringForKey:@"id"];
    if(linkType==CLList_sliders){
        CLSlidersViewController *slider=[CLSlidersViewController new];
        slider.itemId=itemId;
        [[CLPushAnimatedRight sharedInstance] pushController:slider];
        
    }else if(linkType==CLList_doc){
        CLDocViewController *doc=[CLDocViewController new];
        doc.itemId=itemId;
        [[CLPushAnimatedRight sharedInstance] pushController:doc];
    }else if(linkType==CLList_topic){
        CLTopicViewController *topic=[CLTopicViewController new];
        topic.itemId=itemId;
        [[CLPushAnimatedRight sharedInstance] pushController:topic];
    }else if(linkType==CLList_video){
        CLVideoViewController *video=[CLVideoViewController new];
        video.itemId=itemId;
        [[CLPushAnimatedRight sharedInstance] pushController:video];
    }else if(linkType==CLList_audio){
        CLDocViewController *doc=[CLDocViewController new];
        doc.itemId=itemId;
        [[CLPushAnimatedRight sharedInstance] pushController:doc];
    }
    
}


- (BOOL)showPopAction{
    return YES;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
if(!self.entity.relation || [self.entity.relation count]==0) return 0.f;
    return 44.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if(!self.entity.relation || [self.entity.relation count]==0) return nil;
    
       UIView *head=[[UIView alloc] initWithFrame:CGRectMake(0, 0, GlobleWidth, 44.f)];
    head.backgroundColor=[UIColor whiteColor];
    UILabel *title=[[UILabel alloc] initWithFrame:CGRectMake(15, 0, GlobleWidth-30, 44.f)];
    title.font=[UIFont boldSystemFontOfSize:16];
    title.textColor=[UIColor blackColor];
    title.text=[NSString stringWithFormat:@"| %@",@"相关视频"];
    [head addSubview:title];
    
    return head;
    
}



@end
